package com.ht.baselibs.retrofit;

import com.ht.baselibs.bean.BaseErrorBean;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.UIUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by huangtao on 16/9/14.
 */
public abstract class NetCallBack<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {

        hiddenProgress();
        T t = response.body();
        if (response.code() == 200) {

            if (isNullNeedCallback()) {
                onSuccess(call, response);
            } else {
                if (t instanceof BaseErrorBean) {
                    onErrorCodeCallback();
                    onErrorCodeCallbackInfo(response);
                } else {
                    onSuccess(call, response);
                }
            }
        } else {
            onFailure(call, new Exception("response code is " + response.code()));
        }
    }

    protected void onErrorCodeCallbackInfo(Response<T> response) {

    }


    protected void onErrorCodeCallback() {

    }

    protected boolean isNullNeedCallback() {
        return false;
    }

    protected void hiddenProgress() {

    }

    protected abstract void onSuccess(Call<T> call, Response<T> response);

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        hiddenProgress();
        LogUtils.error(t);
        UIUtils.showToast("网络异常，请稍候再试。");
    }
}
